package com.example.statistics.ui.print

import android.R.attr.data
import android.annotation.SuppressLint
import android.bluetooth.*
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.content.Context
import android.content.IntentFilter
import android.os.Bundle
import android.printservice.PrintService
import android.util.Log
import com.example.statistics.R
import com.example.statistics.common.BaseActivity
import com.example.statistics.ex.slimAdapter
import kotlinx.android.synthetic.main.activity_print.*
import kotlinx.coroutines.*
import org.jetbrains.anko.toast


class PrintActivity : BaseActivity() {

    val TAG = "bluetooth"
    /* private val receiver = object : BroadcastReceiver() {
         override fun onReceive(context: Context?, intent: Intent?) {
             val action = intent?.action
             if (action == BluetoothDevice.ACTION_FOUND) {
                 val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                         ?: return
                 if (device.bondState == BluetoothDevice.BOND_BONDED) { //连接过的设备
                     textView.append("\n" + device.name + "-->" + device.address)
                 } else if (device.bondState != BluetoothDevice.BOND_BONDED) { //未连接过的设备
                     textView3.append("\n" + device.name + "-->" + device.address)
                 }


                 *//*
                 if (device.name != null) {//没有名称时不添加
                     val str = "名称: " + device.name + " 地址:" + device.address
                     if (list.indexOf(str) != -1) {
                         list.add(str)
                     }
                 }*//*
            } else if (action == BluetoothAdapter.ACTION_DISCOVERY_STARTED) {
                toast("正在扫描，请耐心等待")
            } else if (action == BluetoothAdapter.ACTION_DISCOVERY_FINISHED) {
                toast("搜索完成")
                textView2.text = "搜索完成"
            }
        }
    }*/

    private var bluetoothDevice: BluetoothDevice? = null
    private var bluetoothGatt: BluetoothGatt? = null
    val callback = object : BluetoothGattCallback() {
        override fun onConnectionStateChange(gatt: BluetoothGatt?, status: Int, newState: Int) {
            super.onConnectionStateChange(gatt, status, newState)
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                //连接成功，开始搜索服务，一定要调用此方法，否则获取不到服务
                Log.e("bluetooth", gatt?.device?.name + " connect successfully");
                gatt?.discoverServices()

                Log.e(TAG, "sendData: 发送数据")
                /*mCharacteristic.setValue(setValue())
                bluetoothGatt?.writeCharacteristic(mCharacteristic)*/
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {   //蓝牙断开连接
                if (bluetoothGatt != null) {//重新连接
                    //关闭当前新的连接
                    gatt?.close();
                    // bluetoothGattCharacteristic = null;
                    connect(bluetoothDevice)
                }
            }
        }


        override fun onCharacteristicWrite(gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic?, status: Int) {
            super.onCharacteristicWrite(gatt, characteristic, status)
            Log.e("bluetooth", gatt?.device?.name + " write successfully");
        }

        override fun onCharacteristicRead(gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic?, status: Int) {
            super.onCharacteristicRead(gatt, characteristic, status)
            val value = characteristic?.value?.toString()
            Log.e("bluetooth", gatt?.device?.name + " recieved " + value);
        }

        override fun onCharacteristicChanged(gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic?) {
            super.onCharacteristicChanged(gatt, characteristic)
            val response = characteristic?.value?.toString()
            Log.e("bluetooth", "The response is $response");
        }

        /* //此方法需先调用gatt.discoverServices();才会回调
         override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) {
             super.onServicesDiscovered(gatt, status)
             //发现服务
             if (status == BluetoothGatt.GATT_SUCCESS) {
                 //蓝牙模块提供的负责通信UUID字符串
                 val service = gatt?.getService(SERVICE_UUID);
                 if (service != null) {
                     //写数据的服务和特征
                     val write = service.getCharacteristic(UUID);

                     //读取数据的服务和特征
                     val read = service.getCharacteristic(UUID);
                     if (read != null) {
                         //订阅读取通知
                         gatt.setCharacteristicNotification(read, true);
                         val descriptor = read.getDescriptor(READ_UUID);
                         descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                         gatt.writeDescriptor(descriptor);
                     }
                 }
             } else {
                 Log.v(TAG, "没有发现蓝牙服务");
             }

         }*/

        override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) {
            super.onServicesDiscovered(gatt, status)
            val serviceList = gatt?.services //获取设备里的全部服务List集
            if (serviceList != null) {
                serviceList[0].uuid

            }

        }
    }


    override val title: String
        get() = "蓝牙"

    @SuppressLint("HardwareIds")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_print)

        val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager;
        val bluetoothAdapter = bluetoothManager.adapter ?: return //当前设备不支持蓝牙 ， 反之
        if (!bluetoothAdapter.isEnabled) {
            bluetoothAdapter.enable()
        }

        val filter = IntentFilter()
        filter.addAction(BluetoothDevice.ACTION_FOUND)//发现设备
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED)//配对
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)//搜索结果
        filter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)
        //registerReceiver(receiver, filter)

        if (!bluetoothAdapter.isEnabled) {
            bluetoothAdapter.enable()
        }

        val adapter = slimAdapter<BluetoothDevice>(R.layout.list_item_common_display) { device ->
            val state = if (device.bondState == BluetoothDevice.BOND_BONDED) "已配对" else "未配对"

            this.text(R.id.tv_title, device.name + "-->" + device.address + state)
                    .clicked {
                        bluetoothGatt = device.connectGatt(this@PrintActivity, false, callback)

                    }
        }
        adapter.attachTo(recycler_view)

        GlobalScope.launch(Dispatchers.Main) {
            scanner(bluetoothAdapter) { device ->
                //textView3.append("\n" + device.name + "-->" + device.address)
                adapter.addData(device)
            }
        }

        val device: BluetoothDevice? = null
        device?.connectGatt(this, false, callback)


        /*  val name = bluetoothadapter.name //本机蓝牙名称
          val address = bluetoothadapter.address //本机蓝牙地址
          val devices = bluetoothadapter.bondedDevices //获取当前设备蓝牙已经连接的设备信息
          val isEnabled = bluetoothadapter.isEnabled //蓝牙是否开启
          val enable = bluetoothadapter.enable() //开启蓝牙
          val disable = bluetoothadapter.disable()// 关闭蓝牙
          val isDiscovering = bluetoothadapter.isDiscovering //当前蓝牙是否正在进行搜索
          val startDiscovery = bluetoothadapter.startDiscovery() //开启搜索附近蓝牙设备
          val cancelDiscovery = bluetoothadapter.cancelDiscovery()// 关闭搜索附近蓝牙设备*/

        //配对

        /*   val method: Method = BluetoothDevice::class.java.getMethod("createBond")
           method.invoke(list.get(i)) //这里面的参数就是BluetoothDevice  */


        //取消配对

        /* val method = BluetoothDevice::class.java.getMethod("removeBond")
         method.invoke(list.get(i)) //这里面的参数就是BluetoothDevice */


    }

    fun a() {
        object : BluetoothGattCallback() {

        }
    }

    fun connect(device: BluetoothDevice?) {
        if (device != null) {
            bluetoothDevice = device
            bluetoothGatt = device.connectGatt(this@PrintActivity, false, callback)
        }
    }


    private fun setValue(): ByteArray? {
        val data = ByteArray(20)
        data[0] = 0xAB.toByte()
        data[1] = 0x00.toByte()
        data[2] = 0x00.toByte()
        data[3] = 0xff.toByte()
        data[4] = 0x31.toByte()
        data[5] = 0x09.toByte()
        data[6] = 0x01.toByte()
        data[7] = 0x00.toByte()
        data[8] = 0x00.toByte()
        data[9] = 0x00.toByte()
        data[10] = 0x00.toByte()
        data[11] = 0x00.toByte()
        data[12] = 0x00.toByte()
        data[13] = 0x00.toByte()
        data[14] = 0x00.toByte()
        data[15] = 0x00.toByte()
        data[16] = 0x00.toByte()
        data[17] = 0x00.toByte()
        data[18] = 0x00.toByte()
        data[19] = 0x00.toByte()
        return data
    }


    private suspend fun scanner(bluetoothAdapter: BluetoothAdapter, body: (BluetoothDevice) -> Unit) {
        val scanner = bluetoothAdapter.bluetoothLeScanner
        val deviceList = mutableListOf<BluetoothDevice>()
        withContext(Dispatchers.IO) {
            val callback = object : ScanCallback() {
                override fun onBatchScanResults(results: MutableList<ScanResult>?) {
                    super.onBatchScanResults(results)
                }

                override fun onScanFailed(errorCode: Int) {
                    super.onScanFailed(errorCode)
                    toast("扫描失败")
                }

                override fun onScanResult(callbackType: Int, result: ScanResult?) {
                    super.onScanResult(callbackType, result)
                    val device = result?.device
                    if (device != null && !deviceList.contains(device)) {
                        body(device)
                        deviceList.add(device)
                    }
                }
            }
            scanner.startScan(callback)
            delay(5000)
            scanner.stopScan(callback)
        }
        /* GlobalScope.launch(Dispatchers.IO) {

             withContext(Dispatchers.Main) {
                 deviceList.forEach { device ->
                     textView3.append("\n" + device.name + "-->" + device.address)
                 }
             }
         }*/
    }

    val list = mutableListOf<String>()

    /**
     *注释：
     * 广播，寻找其他蓝牙设备
     */


    /* private BroadcastReceiver searchDevices = new BroadcastReceiver()
     {
         public void onReceive(Context context, Intent intent) {
             String action = intent . getAction ();
             if (action.equals(BluetoothDevice.ACTION_FOUND)) { //found device
                 BluetoothDevice device = intent . getParcelableExtra (BluetoothDevice.EXTRA_DEVICE);
                 if (device.getName() != null) {//没有名称时不添加
                     String str = "名称: "+device.getName()+" 地址:"+device.getAddress();
                     System.out.println("BlueTooth搜索到的设备:" + str);
                     //如果List中没有str元素则返回-1
                     if (myEveryList.indexOf(str) == -1) {// 防止重复添加
                         myEveryList.add(device); // 获取设备名称和mac地址
                     }
                 }
             } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_STARTED)) {
                 Toast.makeText(getBaseContext(), "正在扫描，请耐心等待", Toast.LENGTH_SHORT).show();
                 tv_now_search.setVisibility(View.VISIBLE);//显示等待标识
                 lv_every.setVisibility(View.GONE);//列表先隐藏掉
                 tv_fu.setText("附近的蓝牙设备(" + myEveryList.size() + ")");
             } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
                 tv_now_search.setVisibility(View.GONE);//隐藏等待标识
                 lv_every.setVisibility(View.VISIBLE);//列表显示
                 Toast.makeText(getBaseContext(), "扫描完成，点击列表中的设备来尝试连接", Toast.LENGTH_SHORT).show();
                 tv_fu.setText("附近的蓝牙设备(" + myEveryList.size() + ")");
                 lv_every.setAdapter(new MyFuListAdapter (myEveryList));
             }
         }
     };*/


}